// 通用的React Hooks

import { useState, useEffect, useCallback } from 'react';
import { checkServerStatus } from '../utils/server';

// 服务器状态管理Hook
export function useServerStatus(url: string, checkInterval: number = 30000) {
  const [serverRunning, setServerRunning] = useState<boolean | null>(null);
  const [lastChecked, setLastChecked] = useState<number>(0);

  const checkServer = useCallback(async () => {
    const running = await checkServerStatus(url);
    setServerRunning(running);
    setLastChecked(Date.now());
    return running;
  }, [url]);

  useEffect(() => {
    checkServer();
    
    const interval = setInterval(checkServer, checkInterval);
    return () => clearInterval(interval);
  }, [checkServer, checkInterval]);

  return {
    serverRunning,
    lastChecked,
    recheckServer: checkServer,
  };
}

// 批量操作状态管理Hook
export interface BatchOperationState<T> {
  items: T[];
  isRunning: boolean;
  step: 'setup' | 'running' | 'completed';
  progress: number;
}

export function useBatchOperation<T>() {
  const [state, setState] = useState<BatchOperationState<T>>({
    items: [],
    isRunning: false,
    step: 'setup',
    progress: 0,
  });

  const startBatch = useCallback(() => {
    setState(prev => ({
      ...prev,
      isRunning: true,
      step: 'running',
      items: [],
      progress: 0,
    }));
  }, []);

  const addItem = useCallback((item: T) => {
    setState(prev => ({
      ...prev,
      items: [...prev.items, item],
    }));
  }, []);

  const updateItem = useCallback((index: number, updates: Partial<T>) => {
    setState(prev => ({
      ...prev,
      items: prev.items.map((item, i) => 
        i === index ? { ...item, ...updates } : item
      ),
    }));
  }, []);

  const updateProgress = useCallback((progress: number) => {
    setState(prev => ({
      ...prev,
      progress: Math.min(100, Math.max(0, progress)),
    }));
  }, []);

  const completeBatch = useCallback(() => {
    setState(prev => ({
      ...prev,
      isRunning: false,
      step: 'completed',
      progress: 100,
    }));
  }, []);

  const resetBatch = useCallback(() => {
    setState({
      items: [],
      isRunning: false,
      step: 'setup',
      progress: 0,
    });
  }, []);

  return {
    ...state,
    startBatch,
    addItem,
    updateItem,
    updateProgress,
    completeBatch,
    resetBatch,
  };
}

// 本地存储Hook
export function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    try {
      if (typeof window !== 'undefined') {
        const item = window.localStorage.getItem(key);
        return item ? JSON.parse(item) : initialValue;
      }
      return initialValue;
    } catch (error) {
      console.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

  const setValue = useCallback((value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      
      if (typeof window !== 'undefined') {
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
      }
    } catch (error) {
      console.warn(`Error setting localStorage key "${key}":`, error);
    }
  }, [key, storedValue]);

  return [storedValue, setValue] as const;
}

// 防抖Hook
export function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(handler);
    };
  }, [value, delay]);

  return debouncedValue;
}

// 异步操作状态Hook
export interface AsyncState<T> {
  data: T | null;
  loading: boolean;
  error: Error | null;
}

export function useAsync<T>() {
  const [state, setState] = useState<AsyncState<T>>({
    data: null,
    loading: false,
    error: null,
  });

  const execute = useCallback(async (asyncFunction: () => Promise<T>) => {
    setState({ data: null, loading: true, error: null });

    try {
      const result = await asyncFunction();
      setState({ data: result, loading: false, error: null });
      return result;
    } catch (error) {
      const errorObj = error instanceof Error ? error : new Error(String(error));
      setState({ data: null, loading: false, error: errorObj });
      throw errorObj;
    }
  }, []);

  return {
    ...state,
    execute,
  };
}
